//
//  MSMusicSearchTool.m
//  HelloMusic
//
//  Created by mac on 15/3/19.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

#import "MSMusicTool.h"
#import "MSMusicSearchResponse.h"
#import "MSSimpleNetWork.h"
#import "GPJSonModel.h"
#import "MSMusicInfoRequest.h"
#import "PropertyTool.h"
#import "MSMusicInfo.h"
#import "MSMusic.h"

@implementation MSMusicTool

// 搜索的URL 5.6.0.1
static NSString *KEYWORD_URI = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=ios&version=5.6.0.1&method=baidu.ting.search.catalogSug&format=json&query=";
// 用来搜索歌手的图片信息
static NSString *PHOTO_URI = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=ios&version=2.4.0&format=json&method=baidu.ting.artist.getInfo&tinguid=";

// 搜索歌曲详细信息的 URI
static NSString *MUSIC_INFO_URI = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.search.merge&format=json&query=%@&page_no=%ld&page_size=%ld&type=-1&data_source=0&use_cluster=1";

+ (void)searchWithKeyWord:(NSString *)keyWord complete:(void(^)(MSMusicSearchResponse *response, NSError *error))complete{
    if ( complete == nil || keyWord == nil ) { return; }
    NSString *url = [NSString stringWithFormat:@"%@%@",KEYWORD_URI,keyWord];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [MSSimpleNetWork requestJSONWithURL:url complete:^(id jsonData, NSError *error) {
        if ( error == nil ) {
            __block id dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL];
            // 获取歌手详细信息
            dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
            dispatch_async(queue, ^{
                __block BOOL success = YES;
                dispatch_group_t group = dispatch_group_create();
                NSMutableArray *array = [NSMutableArray arrayWithArray:dict[@"artist"]];
                
                for ( NSInteger i = 0; i < [array count]; i++ ) {
                    NSDictionary *item = array[i];
                    NSInteger artistid = [item[@"artistid"] integerValue];
                    dispatch_group_async(group, queue, ^{
                        dispatch_group_enter(group);
                        [self requstArtistInfoWithId:artistid complete:^(NSDictionary *result, NSError *error) {
                            if ( result ){
                                NSMutableDictionary *itemResultDict = [NSMutableDictionary dictionaryWithDictionary:item];
                                [itemResultDict addEntriesFromDictionary:result];
                                array[i] = itemResultDict;
                            } else {
                                success = NO;
                            }
                            dispatch_group_leave(group);
                        }];
                    });
                }
                dispatch_group_notify(group, queue, ^{
                    dict = [NSMutableDictionary dictionaryWithDictionary:dict];
                    dict[@"artist"] = array;
                    for (NSDictionary *item in array) {
//                        MSLog(@"%@",item[@"avatar_big"]);
                    }
                    
                    dispatch_main_async_safe( ^{
                        if ( success ) {
                            MSMusicSearchResponse *response = [MSMusicSearchResponse gp_objectWithDictionary:dict];
                            complete(response, nil);
                        } else {
                            complete(nil, nil);
                        }
                    } );
                });
            });
        } else {
            complete(nil, error);
        }
    }];
}

+ (void)requstArtistInfoWithId:(NSInteger)artistid complete:(void(^)(NSDictionary *result, NSError *error))complete {
    NSString *urlString = [NSString stringWithFormat:@"%@%ld",PHOTO_URI,artistid];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [MSSimpleNetWork requestJSONWithURL:urlString completeToCurrThread:^(id jsonData, NSError *error) {
        if ( error ) {
            complete(nil, error);
        } else {
            id artistInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL];
            complete(artistInfo, nil);
        }
    }];
}

@end

@implementation MSMusicTool(MusinInfo)

+ (void)requestMusinInfoWithRequest:(MSMusicInfoRequest *)request complete:(void(^)(NSArray *musicInfos, NSError *error))complete{
    if ( request.query == nil ) return;
    NSString *urlString = [NSString stringWithFormat:MUSIC_INFO_URI,request.query, request.page_no, request.page_size];
    MSLog(@"%@",urlString);
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [MSSimpleNetWork requestJSONWithURL:urlString complete:^(id jsonData, NSError *error) {
        if ( error ) {
            complete(nil, error);
            return;
        }
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL];
        NSArray *info = dict[@"result"][@"song_info"][@"song_list"];
        NSMutableArray *musicInfos = [NSMutableArray arrayWithCapacity:info.count];
        for (NSDictionary *dict in info) {
            MSLog(@"%@",[dict[@"song_id"] class]);
           MSMusicInfo *info = [MSMusicInfo gp_objectWithDictionary:dict];
           [musicInfos addObject:info];
        }
        if (complete) {
            complete(musicInfos, nil);
        }
    }];
}

@end

static NSString *MP3_URI = @"http://music.baidu.com//data/music/links?songIds=%@";

@implementation MSMusicTool(Song)

+ (void)requestMusicWithSongId:(NSString *)song_id complete:(void(^)(MSMusic *music, NSError *error))complete{
    NSString *urlString = [NSString stringWithFormat:MP3_URI,song_id];
    
    NSLog(@"%@",urlString);
    [MSSimpleNetWork requestJSONWithURL:urlString complete:^(id jsonData, NSError *error) {
        if ( error ) {
            complete(nil, error);
            return;
        }
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL];
        NSDictionary *musicDict = dict[@"data"][@"songList"][0];
        MSMusic *music = [MSMusic gp_objectWithDictionary:musicDict];
        complete(music,nil);
    }];
}

@end
